
import random
import time
import serial
import random
import datetime
import _thread
import json
import re
import contextvars
import sys
from pathlib import Path
sys.path.append(str(Path(__file__).parent.parent))
from Utils.varStationConfig import VarStationConfig as varConfig
import threading
import paramiko

# urlArr = varConfig().urlArr
dutArr = varConfig().dutArr

mutex = _thread.allocate_lock()

ssh = paramiko.SSHClient()

def ssh_login(ip, port, username, passwd):
    global ssh
    ssh = paramiko.SSHClient()
    ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
    ssh.connect(ip, port, username, passwd)
    return
    
def ssh_exe_cmd(cmd):
    global ssh
    stdin, stdout, stderr = ssh.exec_command(cmd)
    str1 = stdout.read().decode('utf-8')
    print(str1)
    return

def openSSHTarget(param):

    ssh_login(add, 22, user, passwd)
    return
  
def sendSSHCommand(param):
    #ssh_login('192.168.2.2', 22, 'mark.xiaoj', '123456')
    cmd = param["Commands"]
    try:
        ssh_exe_cmd(cmd)
    except:
        print("SSH connect not open")
    # ssh_exe_cmd('ifconfig')
    #ssh.close()
    return

def closeSSHTarget(param):
    ssh.close()
    return


def openDUT(param):
    try:
        GroupIndex = threading.currentThread().getName()
        print("-----gggg----",GroupIndex)
        DUT = dutArr[int(GroupIndex)]
        print("Dut ========",DUT)
        DUT.open()
        if(DUT.isOpen()): 
            print("open serial sucess")
        else:
            print("open serial fail")
        return True
    except Exception as e:
        print("open dut error:",e)

def closeDUT(param):
    try:
        GroupIndex = threading.currentThread().getName()
        print("-----gggg----",GroupIndex)
        DUT = dutArr[int(GroupIndex)]
        if(DUT.isOpen()): 
            DUT.close()
            print("close serial sucess")
        else:
            print(" serial already closed")
        return True
    except Exception as e:
        print("close dut error:",e)

def sendDutCommand(paraTab):
    return sendDutCommandNumber(paraTab)

def sendDutCommandNumber(paraTab):
    # try:
        # mutex.acquire()
        def args_is_exist(AdditionalParameters,arg):
            if arg == "delimiter":
                delimiter = ":-)"
            if arg == "sleep":
                result = 0.2
            else:
                result = ""
            try:
                result = AdditionalParameters[arg]
               
            except:
                pass
            return result   

        GroupIndex = threading.currentThread().getName()
        DUT = dutArr[int(GroupIndex)]
        receive_msg = ""
        timeout = int(paraTab["Timeout"])
        AdditionalParameters = json.loads(paraTab["AdditionalParameters"])
        
        delimiter = args_is_exist(AdditionalParameters,"delimiter")
        sleep_time = args_is_exist(AdditionalParameters,"sleep")
        expect = args_is_exist(AdditionalParameters,"expect")
        print("sleep time:",sleep_time)
        print("timeout:",timeout)
        print("expect:",expect)

        DUT.timeout = timeout
        
        # if paraTab["Commands"] == "syscfg print SrNm":
        #     expect = "SrNm: \"(.*)\""
        
        sendCommands = paraTab["Commands"] + "\n"
        
        print("send command :",sendCommands)
        DUT.write(sendCommands.encode())
        time.sleep(sleep_time)
        startTime = datetime.datetime.now()
        while True:
            data = DUT.read_all().decode()
            if data:
                receive_msg += data
            else:
                break

        print("[---recvData]---"+receive_msg)
        # mutex.release()
        
        if len(expect) == 0 :
            return True
        else:
            import re
            pattern = re.compile(expect)
            expectValue = pattern.findall(receive_msg)
            print("result:",expectValue)
            if len(expectValue) >0:
                # return True
                # number = float(expectValue[0])
                print('expectValue list is :',expectValue)
                print('expectValue list is :',expectValue[0])
                return expectValue[0]
            else:
                return False
        
def send(cmd):
    GroupIndex = threading.currentThread().getName()
    DUT = dutArr[int(GroupIndex)]
    if(DUT.isOpen()):
        cmd=cmd+'\n'
        DUT.write(cmd.encode('utf-8'))
        #print("send cmd sucess",cmd)
        DUT.flush()
    else:
        print("Serial port %s is closed", DUT.port)
    return True

def sleepForSec(param):
    # print("call sleepForSec")
    # print(param)
    command = param["Commands"]
    # time.sleep(command)
    import os
    os.system(command)
    return True
def sleepForSec1(param):
    # print("call sleepForSec1")
    # print(param)
    time.sleep(1)
    number = random.randint(1,1000)
    return number
def init1(param):
    # print("call init1")
    # print(param)
    time.sleep(1)
    number = random.randint(1,1000)
    return number

def readResponse():
    GroupIndex = threading.currentThread().getName()
    DUT = dutArr[int(GroupIndex)]
    if DUT.isOpen:
            rxdata = bytearray(b'')
            timeBegin = time.time()
            while ((time.time() - timeBegin) < DUT.timeout):
                
                data = DUT.read_all()
                if data:
                    rxdata += bytearray(data)
            else:
                print("Command response timeout")
            
    else:
        raise RuntimeError("Serial port --- {} is closed".format(DUT.port) )
    rxdata = rxdata.decode('utf-8')
    # print(rxdata)
    return rxdata 
def Recive_data_noDelimiter():
    GroupIndex = threading.currentThread().getName()
    DUT = dutArr[int(GroupIndex)]
    receive_msg = ""
    try:      
        receive_msg = DUT.read_all().decode()
        return receive_msg 
    except Exception as e:
        print('Recive_data_noDelimiter error:',e)
        print("------455555555555-------------")
        return False

def enterDiags(param):
    print(">>>>>>>>>>>>>>>>enter Diags<<<<<<<<<<<<<<<<<<<<")
    resp = ""
    for i in range(1000):
        send("\r")
        resp = Recive_data_noDelimiter()
        time.sleep(0.2)
        print("ssssss"+str(i)+":>>"+str(resp))
        if(":-)" in resp):
            print("111----",resp)
            break

        # else:
            # print("222----",resp)
            
        # send diags    
        send("diags")
        resp = readResponse()
        print(">>>>>>>>>>>>")
        print(resp)
        return True

function_dic = {
                "sleepForSec":sleepForSec,
                "sleepForSec1":sleepForSec1,
                "init1":init1,
                "openDUT":openDUT,
                "openDUT":openDUT,
                "send":send,
                "readResponse":readResponse,
                "enterDiags":enterDiags,
                "sendDutCommand":sendDutCommand,
                "closeDUT":closeDUT,
                "sendDutCommandNumber":sendDutCommandNumber
                }